package com.yzp.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @title: 本地负载均衡
 * @Author: yzp
 * @Date: 2019/9/27 22:33
 * @Version 1.0
 */
@RestController
public class ExtRibbonController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    private int requestCount = 1;

    @RequestMapping("/discoveryClient")
    public String discoveryClient() {

        String serviceUrl = getServiceUrl() + "/userManagement/getInfo";
        if (StringUtils.isEmpty(serviceUrl)) {
            return "请求地址为null";
        }
        // 请求地址
        System.out.println("serviceUrl:" + serviceUrl);
        String result = restTemplate.getForObject(serviceUrl, String.class);
        return result;
    }

    @RequestMapping("/getServiceUrl")
    private String getServiceUrl() {
        List<ServiceInstance> instances = discoveryClient.getInstances("micro-user");
        if (instances == null || instances.size() == 0) {
            return null;
        }
        int size = instances.size();
        int index = requestCount % size;
        requestCount++;
        return instances.get(index).getUri().toString();
    }
}
